-- 定时器

local skynet = require "skynet"
local filelog = require "filelog"
local timer = require "timer"
local tabletool = require "tabletool"
local base = require "base"
local timetool = require "timetool"
require "cpcqsscenum"

local filename = "tabletimer.lua"

local json = require "cjson"
json.encode_sparse_array(true, 1, 1)

local TableTimer = {}
local CMD = { }
local service = {}
local tableobj = nil
local tablelogic = nil
local gamelogic = nil

--[Comment]
-- init
--
function TableTimer.init(caller)
	service = caller
	tableobj = service.table_data
	tablelogic = service:get_logicbyname("tablelogic")
	gamelogic = service:get_logicbyname("gamelogic")
end

--[Comment]
-- 处理发来的timer命令消息
--
function TableTimer.timer( msgname, ...)
    local f = CMD[msgname]
    if f == nil then
        return
    end
    return f(...)
end

-----------------------------

--[Comment]
-- 一局游戏开始
--
function CMD.onegamestart(timerid, request)
    if timerid ~= tableobj.timer_id then
		return
	end
    tableobj.timer_id = -1

    if tableobj.state ~= ECQSSCTableState.TABLE_STATE_WAIT_ONE_GAME_START then
        return
    end

    tableobj.state = ECQSSCTableState.TABLE_STATE_ONE_GAME_START
    gamelogic.run(tableobj.gameobj)
end

--[Comment]
-- 摇骰子
--
function CMD.shake_dice(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end
    tableobj.timer_id = -1

	if tableobj.state ~= ECQSSCTableState.TABLE_STATE_WAIT_SHAKE_DICE then
		return
	end
	
	tableobj.state = ECQSSCTableState.TABLE_STATE_SHAKE_DICE
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 玩家下注
--
function CMD.playerbet(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end
    tableobj.timer_id = -1

	if tableobj.state ~= ECQSSCTableState.TABLE_STATE_WAIT_PLAYER_BET then
		return
	end
	
    tableobj.state = ECQSSCTableState.TABLE_STATE_PLAYER_BET
	gamelogic.run(tableobj.gameobj)	
end


---封盘
function CMD.stopbet(timerid, request)
    if timerid ~= tableobj.timer_id then
        return 
    end
    tableobj.timer_id = -1
    if tableobj.state ~= ECQSSCTableState.TABLE_STATE_WAIT_STOP_BET then
        return 
    end

    --统计下注玩家数,总下注次数
    tableobj.cur_bet_player_num = 0
    tableobj.cur_total_bet_cnt = 0
    tableobj.cur_player_total_bet_cnt = 0
    tableobj.cur_robot_total_bet_cnt = 0
    for _,seat in pairs(tableobj.seats) do
        if seat.state > ECQSSCSeatState.SEAT_STATE_NO_PLAYER and seat.rid > 0 and seat.had_ready then
            if seat.cur_bet_list and seat.cur_total_bet > 0 then
                seat.state = ECQSSCSeatState.SEAT_STATE_PLAYING
                tableobj.cur_bet_player_num = tableobj.cur_bet_player_num + 1
                tableobj.cur_total_bet_cnt = tableobj.cur_total_bet_cnt + seat.cur_bet_cnt
                if seat.is_robot then
                    tableobj.cur_robot_total_bet_cnt = tableobj.cur_robot_total_bet_cnt + seat.cur_bet_cnt
                else
                    tableobj.cur_player_total_bet_cnt = tableobj.cur_player_total_bet_cnt + seat.cur_bet_cnt
                end
            elseif seat.is_banker then
                seat.cur_bet_list = tablelogic.gen_bet_list(tableobj)
                seat.state = ECQSSCSeatState.SEAT_STATE_PLAYING
            else
                seat.state = ECQSSCSeatState.SEAT_STATE_INGAME_WATCH
            end
        end
    end
    
    --统计总下注值
    tableobj.cur_total_bet_num = 0
    tableobj.cur_robot_total_bet_num = 0
    tableobj.cur_player_total_bet_num = 0
    for k,v in pairs(tableobj.cur_total_bet_list) do
        tableobj.cur_total_bet_num = tableobj.cur_total_bet_num + v
        ---tableobj.cur_robot_total_bet_num = tableobj.cur_robot_total_bet_num + tableobj.cur_robot_total_bet_list[k]
        ---tableobj.cur_player_total_bet_num = tableobj.cur_player_total_bet_num + tableobj.cur_player_total_bet_list[k]
    end

    tableobj.state = ECQSSCTableState.TABLE_STATE_STOP_BET
    gamelogic.run(tableobj.gameobj)
end


--[Comment]
-- 执行转动
--
function CMD.openaward(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end
    tableobj.timer_id = -1
    
	if tableobj.state ~= ECQSSCTableState.TABLE_STATE_WAIT_OPEN_AWARD then
		return
	end
    tableobj.state = ECQSSCTableState.TABLE_STATE_OPEN_AWARD
    gamelogic.run(tableobj.gameobj)
end

--[Comment]
-- 处理转动结果
--
function CMD.handle_awardresult(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end
    tableobj.timer_id = -1

	if tableobj.state ~= ECQSSCTableState.TABLE_STATE_WAIT_HANDLE_OPEN_AWARD_RESULT then
		return
	end
    local curr_table = base.strsplit(tableobj.cur_qishu, "-")
    local curr_qihao = "" .. curr_table[1] .. curr_table[2]
    tableobj.get_lottery_result_from_url = {}
    ---获取开奖结果
    ---去获取结果
    --[[
    skynet.fork(function()
        while #tableobj.get_lottery_result_from_url ~= 5 do
            tableobj.get_lottery_result_from_url = {}
            ---filelog.sys_error("----openaward--get_lottery_result_from_url----", tableobj.get_lottery_result_from_url, curr_qihao)
            local get_result = skynet.call(".slotmgr", "lua", "get_lottery_result_by_qihao", curr_qihao)
            if get_result ~= false then
                local status, last_result = skynet.pcall(json.decode, get_result)
                ---filelog.sys_error("-----openaward-----last_result--------", last_result)
                if status == true and last_result and last_result.rows == 2 then
                    if curr_qihao == last_result.data.qihao then
                        local get_points = base.strsplit(last_result.data.data, ",")
                        if #get_points == 5 then
                            -- for index, point in ipairs(get_points) do
                            --     table.insert(tableobj.get_lottery_result_from_url, tonumber(point))
                            -- end
                            for i = 5,1,-1 do
                                table.insert(tableobj.get_lottery_result_from_url, tonumber(get_points[i]))
                            end
                        end
                    end
                end
                if #tableobj.get_lottery_result_from_url == 5 then
                    filelog.sys_info("----------get_lottery_result--success-------", os.date("%Y%m%d-%H:%M:%S", timetool.get_time()), curr_qihao, get_result)
                    tableobj.state = ECQSSCTableState.TABLE_STATE_HANDLE_OPEN_AWARD_RESULT
                    gamelogic.run(tableobj.gameobj) 
                end 
            end
            skynet.sleep(2 * 100)
        end 
    end)
    --]]
    local gamename = tablelogic.get_gamename(tableobj)
    local comment = tablelogic.create_comment()
    local status, result = skynet.pcall(skynet.call, ".openaward", "lua", "start_open_award", skynet.self(), tableobj.cur_qishu, tableobj.all_player_betinfo)
    if tableobj.opening_betinfo[tableobj.cur_qishu] == nil then
        tableobj.opening_betinfo[tableobj.cur_qishu] = {
            qishu = tableobj.cur_qishu,
            all_player_betinfo = tabletool.deepcopy(tableobj.all_player_betinfo)
        }
    end
    tableobj.state = ECQSSCTableState.TABLE_STATE_HANDLE_OPEN_AWARD_RESULT
	gamelogic.run(tableobj.gameobj)
end

--[Comment]
----一局游戏结束
--
function CMD.onegameend(timerid, request)
	if tableobj.timer_id ~= timerid then
		return
	end
	
	tableobj.timer_id = -1
	tableobj.state = ECQSSCTableState.TABLE_STATE_ONE_GAME_END
	gamelogic.run(tableobj.gameobj)
end


--[Comment]
-- 一局游戏真正结束
--
function CMD.onegamerealend(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end
    tableobj.timer_id = -1

	if tableobj.state ~= ECQSSCTableState.TABLE_STATE_WAIT_ONE_GAME_REAL_END then
		return
	end

	tableobj.state = ECQSSCTableState.TABLE_STATE_ONE_GAME_REAL_END
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 准备
--
function CMD.doready(timerid, request)
	local seat = tableobj.seats[request.seat_index]	
	if seat.rid ~= request.rid then
		return
	end
	if timerid ~= seat.ready_timer_id then 
		return
	end
    seat.ready_timer_id = -1

    --超时自动准备
    local request = { table_index = tableobj.index}
    local roledata = { info = {rid = seat.rid}, money = { diamond = seat.playerinfo.diamond}, }
    local ret = skynet.call(tableobj.table_service,"lua","request","gameready",seat.rid,roledata,request)
    if not ret or ret.retcode ~= nil then
	    seat.ready_to_time = nil
        seat.ready_timeout_time = nil
        if tablelogic.is_diamondtable() or tablelogic.is_cointable() then
            local rid,coin = seat.rid,tablelogic.get_curmoney(seat)
	        tablelogic.passive_standuptable(tableobj, request, seat, EStandupReason.STANDUP_REASON_READYTIMEOUT_STANDUP)	
            tablelogic.passive_leavetable(tableobj,rid,coin)
        end
    end
end

--[Comment]
-- 删除桌子
--
function CMD.delete_table(timerid, request)
    if tableobj.delete_table_timer_id == timerid then
        local timeout = 1
        if tableobj.table_type ~= ECQSSCTableType.TABLE_TYPE_COIN then
            timeout = tableobj.table_persist or 10 --默认10s
        end
        tableobj.delete_table_timer_id = timer.settimer(timeout * 100,"real_delete_table")
    end 
end

--[Comment]
-- 真正删除桌子
--
function CMD.real_delete_table(timerid, request)
    if tableobj.delete_table_timer_id == timerid then
        tableobj.delete_table_timer_id = -1
        --保存游戏记录
        if tableobj.game_records and tableobj.game_records.delete_reason == 0 then
            tableobj.game_records.end_time = tableobj.one_end_time or 0
            tableobj.game_records.final_to_num = tableobj.curr_to_num or 0
            tableobj.game_records.delete_reason = ECQSSCTableDeleteReason.DELETE_REASON_TABLE_NO_PLAYER
        end
        skynet.send(tableobj.table_service,"lua", "delete")
    end 
end

--[Comment]
-- 延迟处理断线重连
--
function CMD.reenter_table(timerid,request)
    local seat = tableobj.seats[request.seat_index]
    tablelogic.reentertable(tableobj,nil,seat)
end

--[Comment]
-- 旁观
--
function CMD.do_watch(timerid, request)
    if not request or request.rid == nil then
        return
    end

    if tableobj.waits[request.rid] ~= nil then
        tablelogic.passive_leavetable(tableobj, request.rid, request.coin)
    end
end

--[Comment]
-- 断线超时
--
function CMD.disconnect_outtime(timerid, request)
    if not request or request.index == nil then
        return
    end

    local seat = tableobj.seats[request.index]
    if not seat then
        return
    end
    seat.disconnect_timer_id = -1

    local rid,coin = seat.rid,tablelogic.get_curmoney(seat)
    tablelogic.passive_standuptable(tableobj, {}, seat, EStandupReason.STANDUP_REASON_DISCONNECTED)	
    tablelogic.passive_leavetable(tableobj,rid,coin)
    
end

--[Comment]
-- 保存记录
--
function CMD.save_records(timerid, request)
    gamelogic.save_records(tableobj)
end

return TableTimer